package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"lesson/api/request"
	"lesson/consts"
	"lesson/internal/dao"
	"lesson/internal/model"
	"lesson/pkg"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	var req request.LoginUser

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}

	var data model.User
	if !dao.GetOneByFields(&model.User{Username: req.Username, Password: req.Password}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "账号密码不正确",
			"data":    nil,
		})
	}

	if data.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "登录失败",
			"data":    nil,
		})
		return
	}

	token, err := pkg.NewJWT(consts.JWT_SECRET_KEY).CreateToken(pkg.CustomClaims{
		ID: data.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*7,
		},
	})

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "登录失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "登录成功",
		"data":    token,
	})

}
